﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harkon.AppServer.cOne.Service;
using Harkon.AppServer.cOne.Events;
using log4net;

namespace Harkon.AppServer.cOne.CommandQueues
{
    public class CommandQueueManager : AbstractService, ICommandQueueManager
    {
        private static ILog _logger = LogManager.GetLogger(typeof(CommandQueueManager));
        public IEventManager EventManager { get; set; }
        private IDictionary<Type, ICommandQueue> _commandQueues = new Dictionary<Type, ICommandQueue>();

        public override bool Init()
        {
            return base.Init();
        }

        public void EnqueueCommand(StandardCommand command)
        {
            ICommandQueue destinationQueue;
            lock (_commandQueues)
            {
                destinationQueue = _commandQueues[command.GetType()];
            }
            if (destinationQueue != null)
            {
                _logger.InfoFormat("Enqueue command {0} in queue {1}", command, destinationQueue);
                destinationQueue.EnqueueCommand(command);
            }
            else
                throw new NoCommandQueueRegistered(command.GetType());
        }

        public void RegisterCommandQueue(ICommandQueue queue)
        {
            lock (_commandQueues)
            {
                if (_commandQueues.ContainsKey(queue.CommandType))
                    throw new CommandQueueTypeAlreadyRegisteredException(queue.CommandType);
                _logger.DebugFormat("Registering queue for type {0}", queue.CommandType);
                _commandQueues.Add(queue.CommandType, queue);
            }

        }
    }
}
